package webServer

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"7qule.com/sd3/CrossServer/src/utils"

	"public.com/Framework/ipMgr"

	"public.com/goutil/logUtil"
	"public.com/goutil/stringUtil"
	"public.com/goutil/webUtil"

	"7qule.com/sd3/CrossServer/src/config"
	"7qule.com/sd3/rpcService/Common"
)

// 定义自定义的Mux对象
type selfDefineMux struct {
}

func (mux *selfDefineMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var resquestData *RequestObject
	responseObj := GetInitResponseObj()
	defer utils.LogReqErrorRecover(resquestData)

	// 判断是否是接口文档
	if strings.Contains(r.RequestURI, "Remarks") && r.Method == "GET" {
		remarkFunc(w, r)
		return
	}

	// 判断是否是POST方法
	if r.Method != "POST" {
		responseResult(w, responseObj.SetResultStatus(Common.ResultStatus_Cross_OnlySupportPOST))
		return
	}

	// 验证IP是否正确
	if config.DEBUG == false && ipMgr.IsIpValid(webUtil.GetRequestIP(r)) == false {
		logUtil.Log(fmt.Sprintf("请求的IP：%s无效", webUtil.GetRequestIP(r)), logUtil.Error, true)
		responseResult(w, responseObj.SetResultStatus(Common.ResultStatus_Cross_IPForbid))
		return
	}

	// 构造contex
	context, errMsg := NewApiContext(r, w, true)
	if errMsg != nil {
		// 输出结果
		responseResult(w, responseObj.SetResultStatus(Common.ResultStatus_Cross_APIDataError))
		return
	}

	// 根据路径选择不同的处理方法
	if handlerFunObj, exists := GetHandleFunc(r.RequestURI); exists {
		defer func() {
			if config.DEBUG {
				b, _ := json.Marshal(responseObj)
				msg := fmt.Sprintf("API:%v 请求数据：%v;返回数据：%s;",
					r.RequestURI, string(context.GetRequestBytes()), string(b))
				logUtil.Log(msg, logUtil.Debug, true)
			}
		}()

		// 输出结果
		responseObj := handlerFunObj.HandleFun()(context)
		responseResult(w, responseObj)
		return
	}

	// 通过反射选择不同的方法
	strs := stringUtil.Split(r.RequestURI, []string{"/"})
	params, err := context.RequestDataBySlice2()
	if err != nil {
		responseResult(w, responseObj.SetResultStatus(Common.ResultStatus_Cross_APIDataError))
		return
	}
	resquestData = NewRequestObject(strs[0], strs[1], params)
	resp := CallFunction(resquestData)
	responseResult(w, resp)
}
